package com.jhs.boot.config;

import com.jhs.boot.system.service.FeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname FeignClientFactory
 * @Description TODO
 * @Date 2025/11/24 15:07
 * @Created by zxy
 */
@Component
@Slf4j
public class FeignClientFactory {
    private final Map<String, FeignService> feignClientCache = new ConcurrentHashMap<>();

    @Autowired
    private FeignConfig feignBuilder;

    public FeignService getFeignClientSafe(String baseUrl) {

        return feignClientCache.computeIfAbsent(baseUrl, url ->
                feignBuilder.getFeignClient( baseUrl)
        );
    }

    public void removeFeignClient(String baseUrl) {
        log.info("成功移除Feign客户端，URL: {}", baseUrl);
        feignClientCache.remove(baseUrl);
    }
    /**
     * 安全地获取Feign客户端，包含验证
     */
    public FeignService getFeignClient(String baseUrl) {
        try {
            // 验证URL格式
            validateBaseUrl(baseUrl);
            FeignService client = getFeignClientSafe(baseUrl);

            // 验证客户端是否有效
            // 添加调试信息
            if (log.isDebugEnabled()) {
                log.debug("Feign client proxy class: {}", client.getClass().getName());
            }
            // 验证客户端是否可用
            validateFeignClient(client);
            return client;
        } catch (Exception e) {
            // 移除无效的客户端
            feignClientCache.remove(baseUrl);
            throw new RuntimeException("获取Feign客户端失败: " + baseUrl, e);
        }
    }
    /**
     * 验证Feign客户端
     */
    private void validateFeignClient(FeignService client) {
        // 这里不实际调用方法，只是检查代理对象是否创建成功
        if (client == null) {
            throw new IllegalStateException("Feign客户端创建失败");
        }
        // 可以添加其他验证逻辑
        log.debug("Feign客户端验证通过，代理类: {}", client.getClass().getName());
    }

    public void refreshFeignClient(String oldBaseUrl, String newBaseUrl) {
        removeFeignClient(oldBaseUrl);
        getFeignClient(newBaseUrl);
    }
    /**
     * 验证URL格式
     */
    private void validateBaseUrl(String baseUrl) {
        if (baseUrl == null || baseUrl.trim().isEmpty()) {
            throw new IllegalArgumentException("Base URL不能为空");
        }
        if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
            throw new IllegalArgumentException("Base URL必须以http://或https://开头");
        }
    }
    /**
     * 获取缓存信息（用于调试）
     */
    public Map<String, String> getCacheInfo() {
        Map<String, String> info = new HashMap<>();
        for (Map.Entry<String, FeignService> entry : feignClientCache.entrySet()) {
            info.put(entry.getKey(), entry.getValue().getClass().getName());
        }
        return info;
    }
}